<script setup>
import { ref, onMounted, computed } from 'vue'
import LogoImg from '@/assets/img/1.png'
import { showConfirmDialog } from 'vant'
import routes from '@/commons/router'
import { useRoute } from 'vue-router'
import { testedApi, listQstsApi, testExamApi } from '@/commons/api'
import Loader from '@/components/loader/Loader'
import Msg from '@/components/message'
import { nanoid } from 'nanoid'

// 定义是否显示加载中的变量
let loadShow = ref(false)

// 加载后调用监听滚动
onMounted(() => {
  checkInfo()
})

let examId, stud

const studRef  = ref({
  realName: '',
  workNo: '',
  mobile: '18173330471',
  deptName: '',
  examId: ''
})

const checkInfo = async () => {
  examId = useRoute().params.examId
  stud = JSON.parse(localStorage.getItem('stud'))
  if(!examId || examId === '' || examId.length !== 21) {
    Msg({ kind: 'error', txt: '未找到考试的试卷，请联系管理员！' })
    return
  }
  if(!stud || stud.realName==='') {
    Msg({ kind: 'error', txt: '请先填写员工信息！' })
    routes.replace('/login/' + examId)
    return
  }
  studRef.value = stud
  studRef.value.examId = examId
  const res = await testedApi(studRef.value)
  if(res.code === '1000') {
    Msg({ kind: 'warn', txt: '您已经答过题了～！' })
  } else {
    await listQsts()
  }
}
const passTime = ref(0)
const setPassTime = () => {
  passTime.value++
}

const qstList = ref([])
const testTime = ref(1800000)
const listQsts = async () => {
  loadShow.value = true
  try {
    const res = await listQstsApi({ examId })
    if(res.code === '1000') {
      qstList.value = res.data
      let m = 0
      qstList.value.forEach(qst => {
        if(qst.kind === 6) {
          m++
          qst.qstNo = m
          const imgNames = qst.fileNames ? qst.fileNames.split(',') : []
          const imgUrls = qst.fileUrls ? qst.fileUrls.split(',') : []
          qst.fileList = []
          for(let i=0; i<imgNames.length; i++) {
            qst.fileList.push({ name: imgNames[i], url: imgUrls[i] })
          }
          let n = 1
          qst.optList.forEach(opt => {
            opt.optNo = m + '.' + n
            n++
          })
        } else {
          m++
          qst.qstNo = m
        }
      })
      const stud = JSON.parse(localStorage.getItem('stud'))
      testTime.value = stud.examTime * 60 * 1000
      // countdown()
    } else {
      Msg({ kind: 'error', txt: '暂无考试！' })
      routes.replace('/login/' + examId)
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

const fmtKind = computed(() =>{
  return (kind) => {
    switch (kind) {
      case 1:
        return '单选题'
      case 2:
        return '判断题'
      case 3:
        return '多选题'
      case 4:
        return '填空题'
      case 5:
        return '简答题'
      case 6:
        return '实操题'
      default:
        return '其它'
    }
  }
})

const opts = ref([])
const chkOpt = (kind, index, idx) => {
  switch (kind) {
    case 1:
      qstList.value[index].optList.forEach(opt => {
        opt.answer = 2
      })
      qstList.value[index].optList[idx].answer = 1
      qstList.value[index].myAnswer = qstList.value[index].optList[idx].optId
      break
    case 2:
      let opt = qstList.value[index].optList[idx]
      opt.answer = 1
      if (opts.value.indexOf(opt.optId) === -1) {
        opts.value.push(opt.optId)
        qstList.value[index].myAnswer = qstList.value[index].myAnswer ? qstList.value[index].myAnswer + qstList.value[index].optList[idx].optId + ',' : qstList.value[index].optList[idx].optId + ','
      } else {
        opt.answer = 2
        qstList.value[index].myAnswer = qstList.value[index].myAnswer.replace(opt.optId + ',', '')
        opts.value.splice(opts.value.indexOf(opt.optId), 1)
      }
      break
  }
}

const allScore = ref(0)

const testExam = async () => {
  showConfirmDialog({
    title: '确认交卷',
    message: '交卷后不能再进行答题，确认现在就交卷吗？',
  }).then(() => {
    testProc()
  }).catch(() => {
    history.pushState(null, null, '#/test/' + examId )
  })
}

const testProc = async () => {
  loadShow.value = true
  const logId = nanoid()
  let logDetails = []
  qstList.value.forEach(qst => {
    let logDetail = {}
    if((qst.kind===1 || qst.kind===2 || qst.kind===3)) {
      logDetail = {
        detlId: nanoid(),
        logId: logId,
        examId: examId,
        qstId: qst.qstId,
        score: 0.000,
        optId: qst.myAnswer
      }
      if((qst.kind===1 || qst.kind===2) && qst.answer === qst.myAnswer) {
        logDetail.score = parseFloat(qst.score)
        allScore.value += parseFloat(qst.score)
      }
      if(qst.kind === 3) {
        qst.answer = qst.answer.substring(0, qst.answer.length - 1)
        qst.myAnswer = qst.myAnswer && qst.myAnswer.substring(qst.myAnswer.length - 1, qst.myAnswer.length)===',' ? qst.myAnswer.substring(0, qst.myAnswer.length - 1) : ''
        const rightAns = qst.answer.split(',')
        const myAnswer = qst.myAnswer.split(',')
        const correct = rightAns.every(option => myAnswer.includes(option)) && myAnswer.every(option => rightAns.includes(option))
        if(correct) {
          logDetail.score = parseFloat(qst.score)
          allScore.value += parseFloat(qst.score)
        }
      }
      logDetails.push(logDetail)
    }
  //   if((qst.kind===4 || qst.kind===5) && qst.optList && qst.optList.length>0) {
  //     qst.optList.forEach(opt => {
  //       logDetail = {
  //         detlId: nanoid(),
  //         logId: logId,
  //         examId: examId,
  //         qstId: qst.qstId,
  //         score: 0.000,
  //         optId: opt.optId,
  //         answer: opt.myAnswer,
  //         keywords: ''
  //       }
  //       const keywords = opt.keywords.split('@-@')
  //       let myKey = ''
  //       let perScore = parseFloat(opt.izRight) / keywords.length
  //       keywords.forEach(keyword => {
  //         if(opt.myAnswer && opt.myAnswer.indexOf(keyword)>=0) {
  //           logDetail.score += perScore
  //           myKey += keyword + '@-@'
  //           allScore.value += perScore
  //         }
  //       })
  //       myKey = myKey.substring(0, myKey.length - 3)
  //       logDetail.keywords = myKey
  //       logDetails.push(logDetail)
  //     })
  //   }
  //   if(qst.kind===6 && qst.optList && qst.optList.length>0) {
  //     let perScore = qst.score / qst.keywords.split('@-@').length
  //     // 题
  //     qst.optList.forEach(opt => {
  //       logDetail = {
  //         dtlId: nanoid(),
  //         logId: logId,
  //         examId: examId,
  //         qstId: opt.qstId,
  //         answer: '',
  //         fxd: '',
  //         fxdKey: '',
  //         sglx: '',
  //         sglxKey: '',
  //         ffcs: '',
  //         ffcsKey: '',
  //         score: 0.000,
  //         remarks: ''
  //       }
  //       // 答案
  //       qst.optList.some(function(asr) {
  //         let myKey = []
  //         let nums = 0
  //         let keywords = opt.imgNames ? opt.imgNames.split('@-@') : []
  //         keywords.forEach(key =>  {
  //           if(((asr.fxd && asr.fxd.indexOf(key)>=0)) && myKey.indexOf(key)===-1) {
  //             nums++
  //           }
  //         })
  //         if(nums>0 && nums/keywords.length>0.5) {
  //           logDetail.optId = asr.optId
  //           keywords.forEach(key =>  {
  //             if(((asr.fxd && asr.fxd.indexOf(key)>=0)) && myKey.indexOf(key)===-1) {
  //               myKey.push(key)
  //               logDetail.score += perScore
  //               allScore.value += perScore
  //             }
  //           })
  //           // 说明是对应的题
  //           logDetail.fxd = asr.fxd
  //           logDetail.fxdKey = myKey.join('@-@')
  //           myKey = []
  //           keywords = opt.imgUrls ? opt.imgUrls.split('@-@') : []
  //           keywords.forEach(key => {
  //             if(((asr.sglx && asr.sglx.indexOf(key)>=0)) && myKey.indexOf(key)===-1) {
  //               logDetail.score += perScore
  //               myKey.push(key)
  //               allScore.value += perScore
  //             }
  //           })
  //           logDetail.sglx = asr.sglx
  //           logDetail.sglxKey = myKey.join('@-@')
  //           myKey = []
  //           keywords = opt.keywords ? opt.keywords.split('@-@') : []
  //           keywords.forEach(key => {
  //             if(((asr.ffcs && asr.ffcs.indexOf(key)>=0)) && myKey.indexOf(key)===-1) {
  //               logDetail.score += perScore
  //               myKey.push(key)
  //               allScore.value += perScore
  //             }
  //           })
  //           logDetail.ffcs = asr.ffcs
  //           logDetail.ffcsKey = myKey.join('@-@')
  //           myKey = []
  //           return true
  //         }
  //       })
  //       logDetails.push(logDetail)
  //     })
  //   }
  })
  allScore.value = allScore.value<100 ? parseFloat(allScore.value.toFixed(3)) : 100
  const stud = JSON.parse(localStorage.getItem('stud'))
  const examLog = {
    logId: logId,
    realName: stud.realName,
    workNo: stud.workNo,
    mobile: stud.mobile,
    deptName: stud.deptName,
    examId: examId,
    score: allScore.value,
    testTime: passTime.value,
    logDetails: logDetails
  }
  try {
    const res = await testExamApi(examLog)
    if(res.code === '1000') {
      stud.score = allScore.value
      stud.logId = logId
      localStorage.setItem('stud', JSON.stringify(stud))
      logDetails = []
      allScore.value = 0
      routes.replace('/result/' + examId)
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

const autoSubmit = () => {
  Msg({ kind: 'error', txt: '考试时间到，自动交卷！' })
  testProc()
}

const picShow = ref(false)
const imgRef = ref({ name: '', url: '' })
const showPic = (name, url) => {
  imgRef.value.name = name
  imgRef.value.url = url
  picShow.value = true
}
</script>

<template>
  <div class="test-a">
    <div class="test-b">
      <div class="test-c"><img :src="LogoImg" class="w100" alt="logo" /></div>
      <div class="test-d"><i class="iconfont">&#xe8e7;</i> 时间剩余：</div>
      <van-count-down :time="testTime" format="mm 分 ss 秒" @change="setPassTime" @finish="autoSubmit" />
    </div>
    <div class="test-e">
      <div class="test-f" v-for="(qst, index) in qstList" :key="qst.qstId">
        <div class="test-g">{{ qst.qstNo }}.【{{ fmtKind(qst.kind) }}】{{ qst.title }}（{{ qst.score }}分）</div>
        <div class="test-h" v-if="qst.fileList && qst.fileList.length>0">
          <div class="test-i mr15" v-for="img in qst.fileList" @click="showPic(img.name, img.url)"><img :alt="img.name" v-lazy="img.url" class="test-j" /></div>
        </div>
        <div class="test-k" v-for="(opt, idx) in qst.optList" :key="opt.optId">
          <div>
            <span v-if="qst.kind===1 || qst.kind===2" @click="chkOpt(1, index, idx)"><i :class="['iconfont mr15 opt-a', opt.answer===1 ? 'chked' : 'chk']" v-html="opt.answer===1 ? '&#xe891;' : '&#xe89b;'" @click="chkOpt(1, index, idx)" />{{ opt.optNo }}. {{ opt.optName }}</span>
            <span v-if="qst.kind===3" @click="chkOpt(2, index, idx)"><i :class="['iconfont mr15 opt-a', opt.answer===1 ? 'chked' : 'chk']" v-html="opt.answer===1 ? '&#xe8e5;' : '&#xe8c9;'" />{{ opt.optNo }}. {{ opt.optName }}</span>
          </div>
          <div v-if="qst.kind===4 || qst.kind===5">
            <div class="test-g">{{ opt.optNo }}. {{ opt.optName }}（{{ opt.izRight }}分）</div>
            <div class="test-k"><textarea v-model="opt.myAnswer" class="desc-txt"></textarea></div>
          </div>
          <div v-if="qst.kind===6">
            <div class="test-g">{{ opt.optNo }}.1. 风险点</div>
            <div class="test-k"><textarea v-model="opt.fxd" class="desc-txt"></textarea></div>
            <div class="test-g">{{ opt.optNo }}.2. 事故类型</div>
            <div class="test-k"><textarea v-model="opt.sglx" class="desc-txt"></textarea></div>
            <div class="test-g">{{ opt.optNo }}.3. 防范措施</div>
            <div class="test-k"><textarea v-model="opt.ffcs" class="desc-txt"></textarea></div>
          </div>
        </div>
      </div>
    </div>
    <div class="test-l" @click="testExam">交卷</div>
    <van-popup v-model:show="picShow" closeable><img :alt="imgRef.name" v-lazy="imgRef.url" class="w100" /></van-popup>
    <loader :loadShow="loadShow" />
  </div>
</template>

<style>
.test-a {width: 100%; height: 100%; background-color: #f0f0f0; overflow: hidden;}
.test-b {width: calc(100% - 2rem); padding: 1rem; background-color: #FFF; display: -webkit-flex; display: flex; align-items: center; border-bottom: 1px solid #f0f0f0;}
.test-c {width: 2.5rem; height: 2.5rem;}
.test-d {flex-grow: 1; font-size: 1.2rem; color: #333; text-align: right;}
.test-e {height: calc(100% - 6.5rem); background-color: #f2f2f2; overflow: auto;}
.test-f {padding: 1rem; margin: 0.5rem; background-color: #FFF; box-shadow: 1px 1px 3px #CCC;}
.test-g {line-height: 1.6rem;}
.test-h {display: -webkit-flex; display: flex;}
.test-i {width: 90px; height: 90px; overflow: hidden; border: 1px solid #4099FF; border-radius: 4px; text-align: center;}
.test-j {height: 100%;}
.test-k {padding: 0.6rem 1rem;}
.test-l {width: 100%; height: 1.4rem; position: fixed; bottom: 0; padding: 0.8rem 0; color: #FFF; background-color: #2f73ff; box-shadow: 1px -1px 3px #CCC; cursor: pointer; text-align: center; font-size: 1.2rem;}
</style>